<?php
declare (strict_types = 1);
namespace app\api\controller;
use app\api\BaseController;
// use app\api\middleware\Auth;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\facade\Db;
use think\facade\Request;
// 收藏产品
class Collect extends BaseController
{
	protected $middleware = [
    	
    ];
	// 平台收藏列表
	public function index(){
			$userid= request()->param('userid');
			if(!$userid){
				return json(['code'=>400,'msg'=>'参数缺少']);
			}
			$info=Db::name('collect')->alias('c')
			    ->join('schoolproduct p','p.id=c.product_id')
				->join('product d','d.id=p.product_id')
				->where(['c.user_id'=>$userid])
				->field('c.id,d.name,p.price,d.image')
				->select()
				->toArray();
				// print_r($info);exit;
				foreach($info as $k=>$v){
					if (!isHttpsUrlByRegex($v['image'])) {
					   $info[$k]['image']=imgurl($v['image']);
					}
				}
				return json(['code'=>200,'msg'=>'获取成功','data'=>$info]); 
	}
    // 收藏产品
	public function collect(){ 
		if(request()->isPost()){
			$userid= request()->param('userid');
			$platform_id=request()->param('platform_id');
			$product=request()->param('id');
			$info=Db::name('collect')->where(['product_id'=>$product,'user_id'=>$userid,'type_id'=>$platform_id])->find();
			if($info){
				return json(['code'=>400,'msg'=>'已收藏']);
			}else{
				$data['product_id']=$product;
				$data['user_id']=$userid;
				$data['type_id']=$platform_id;
				$data['create_time']=time();
				$data['update_time']=time();
				$info=Db::name('collect')->insert($data);
				if($info){
					return json(['code'=>200,'msg'=>'收藏成功']);
				}else{
					return json(['code'=>400,'msg'=>'收藏失败']);
				}
			}
		 }
	}
    // 取消收藏
	public function cancel(){
		if(request()->isPost()){
			$userid= request()->param('userid');
			$id=request()->param('id');
			$info=Db::name('collect')->where(['user_id'=>$userid,'id'=>$id])->delete();
			if($info){
				return json(['code'=>200,'msg'=>'取消成功']);
			}else{
				return json(['code'=>400,'msg'=>'取消失败']);
			}
		 }
	}
}
